from django.utils.cache import patch_vary_headers
from django.core import urlresolvers
from django.conf import settings
from django import http
from django.utils.http import urlquote 
from django.utils import translation

from _translation import get_language_from_request_l, set_language_into_url#, get_location_from_request


class LocaleMiddleware(object):
    '''Modified django.middleware.locale.LocaleMiddleWare.
    Gets language preference from url.'''
    def process_request(self, request):
        #XX Map IP to country
        language, level = get_language_from_request_l(request) 
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()
        #XX request.LOCATION = ?
        
        if level:
            return language_into_url(request, level)
        
    def process_response(self, request, response):
        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response
    
def _is_valid_path(path, urlconf=None):
    try:
        urlresolvers.resolve(path, urlconf)
        return True
    except urlresolvers.Resolver404:
        return False


def language_into_url(request, level):
    #assert request.path == request.path_info #!! Is this True?
    
    path = request.path
    
    host = request.get_host()
    old_url = [host, path]
    new_url = old_url[:]
    new_path = set_language_into_url(path, request.LANGUAGE_CODE, level)
    
    urlconf = getattr(request, 'urlconf', None)
    redirect = True
    # If path has a wrong language then it is not valid, hence the use of level below.
    if level is 2 and _is_valid_path(path, urlconf):
        redirect = False
    elif _is_valid_path(new_path, urlconf):
        new_url[1] = new_path
    elif settings.APPEND_SLASH and not old_url[1].endswith('/'):
        path = "%s/" % path
        new_path = "%s/" % new_path
        if level is 2 and _is_valid_path(path, urlconf):
            new_url[1] = new_path
        elif _is_valid_path(new_path, urlconf):
            new_url[1] = new_path 
        else:
            redirect = False      
        
    if redirect and settings.DEBUG and request.method == 'POST':
        raise RuntimeError, (""
        "You called this URL via POST, but the URL doesn't have "
        "a supported language code. Django can't redirect to the "
        "URL with a supported language code while maintaining "
        "POST data. Change your form to point to %s%s.") % (new_url[0], new_url[1])  
                
    if new_url == old_url:
        # No redirects required.
        return
    if new_url[0]:
        newurl = "%s://%s%s" % (
            request.is_secure() and 'https' or 'http',
            new_url[0], urlquote(new_url[1]))
    else:
        newurl = urlquote(new_url[1])
    if request.GET:
        newurl += '?' + request.META['QUERY_STRING']
    return http.HttpResponsePermanentRedirect(newurl)